﻿using CardMonitor.Model;
using CardMonitor.Utils;
using CardMonitor.Windows;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;

namespace CardMonitor.Pages
{
    /// <summary>
    /// Account.xaml 的交互逻辑
    /// </summary>
    public partial class Account : Page
    {
        BillModel billModel = null;
        MainWindow mainWindow = null;
        SynchronizationContext _syncContext = null;
        public Account()
        {
            InitializeComponent();

            mainWindow = (MainWindow)Window.GetWindow(this);
        }
        public Account(BillModel billModel, MainWindow _win)
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            this.billModel = billModel;
            
            this.DataContext = billModel;
            mainWindow = _win;
        }

        private void goIndex(object sender, RoutedEventArgs e)
        {
            
            NavigationService.GetNavigationService(this).GoBack();
        }

        private void doAccount(object sender, RoutedEventArgs e)//结算按钮

        {
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            string busiType = ("1".Equals(billModel.Type) ? "sale" : "buy");
            JObject paramJSON = new JObject();
            paramJSON.Add("id", billModel.Id);
            //paramJSON.Add("code", App.getConfig().DeviceCode);
            //paramJSON.Add("name", "自助终端" + App.getConfig().DeviceCode);
            //paramJSON.Add("busiType", busiType);
            httpPostWindow.setParamObject(paramJSON);
            httpPostWindow.setOperation(HttpPostWindow.OperationType.billAccount.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                CardDeviceUtil.PopupCard();
                string message = "结算失败,请到人工窗口办理";
                showMessage(message);               
                NavigationService.GetNavigationService(this).GoBack();
                return;
            }
            JObject resultObj = httpPostWindow.getResultObject();
            if(null != resultObj)
            {
                CardDeviceUtil.PopupCard();
                string message = (string)resultObj["Message"];
                showMessage(message);               
                NavigationService.GetNavigationService(this).GoBack();
                return;
            }
            //httpPostWindow = new HttpPostWindow();
            //paramJSON.RemoveAll();
            //paramJSON.Add("id", billModel.Id);
            //httpPostWindow.setParamObject(paramJSON);
            //httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByID.ToString());
            //result = (bool)httpPostWindow.ShowDialog();
            //if (!result)
            //{
            //    CardDeviceUtil.PopupCard();
            //    string message = "结算失败,请到人工窗口办理";
            //    showMessage(message);               
            //    NavigationService.GetNavigationService(this).GoBack();
            //    return;
            //}
            //JObject resultObjNew = httpPostWindow.getResultObject();
            //BillModel bill = JsonConvert.DeserializeObject<BillModel>(resultObjNew.ToString());

            //if (App.getConfig().IfPrint.Equals("0"))
            //{
            //    PrintWindow printWindow = new PrintWindow();
            //    printWindow.setBillMode(bill);
            //    if ("1".Equals(billModel.Type))
            //    {
            //        printWindow.setTemplete("tplSaleAccountS,tplSaleOutS","1");
            //    }
            //    else
            //    {
            //        printWindow.setTemplete("tplBuyAccountS,tplBuyOutS","1");
            //    }
            //    printWindow.Owner = mainWindow;
            //    printWindow.ShowDialog();
            //}
            

            CardDeviceUtil.ReceiveCard();
            showMessage("结算完成");
            NavigationService.GetNavigationService(this).GoBack();
        }
        private void doPrint()
        {
            Excel.Application ExcelApp = new Excel.Application();
            ExcelApp.Visible = false;//是打开可见
            Excel.Workbooks wbks = ExcelApp.Workbooks;
            Excel._Workbook wbk = wbks.Add(System.AppDomain.CurrentDomain.BaseDirectory+"/Report/test01.xlsx");
            Excel.Worksheet ws = (Excel.Worksheet)wbk.Worksheets[1];
            
            try
            {
                int rows = ws.UsedRange.Rows.Count;
                int columns = ws.UsedRange.Columns.Count;

                for (int i = 1; i <= rows; i++)
                {
                    for(int j=1; j<= columns; j++)
                    {
                        if(null != ws.Cells[i, j] && null != ws.Cells[i, j].Value2)
                        {
                            string _val = ws.Cells[i, j].Value2.ToString();
                            if (!_val.StartsWith("${"))
                            {
                                continue;
                            }
                            switch (_val)
                            {
                                case "${BillCode}":
                                    ws.Cells[i, j] = "00001";
                                    break;
                                case "${CarNo}":
                                    ws.Cells[i, j] = "鲁E00001";
                                    break;
                                case "${TankNo}":
                                    ws.Cells[i, j] = "1#";
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex){
                Console.WriteLine(ex.ToString());
            }
            
            wbk.PrintOutEx();
            
            KillProcess(ExcelApp); //杀掉生成的进程
            GC.Collect(); //垃圾回收机制
        }
        [DllImport("User32.dll")]
        public static extern int GetWindowThreadProcessId(IntPtr Hwnd, out int PID);
        private static void KillProcess(Excel.Application AppObject)
        {
            int Pid = 0;
            IntPtr Hwnd = new IntPtr(AppObject.Hwnd);
            System.Diagnostics.Process p = null;
            try
            {
                GetWindowThreadProcessId(Hwnd, out Pid);
                p = System.Diagnostics.Process.GetProcessById(Pid);
                if (p != null)
                {
                    p.Kill();
                    p.Dispose();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("进程关闭失败！异常信息：" + ex);
            }
        }
        private void showMessage(String message)
        {
            InfoWindow infoWindow = new InfoWindow(message);
            infoWindow.Owner = mainWindow;
            infoWindow.ShowDialog();
        }


    }
}
